<?php
/**
 * Created by PhpStorm.
 * User: cyc
 * Date: 2017/11/2
 * Time: 下午4:45
 */

class ChannelConfigReader implements ConfigReader
{
    private $type;
    private $status;
    private $_orders = array();

    public function __construct($channelType = null, $status = MsggConfig::STATUS_OPEN)
    {
        $this->type = $channelType;
        $this->status = $status;
    }

    public function setOrder($order)
    {
       $this->_orders[] = $order;
    }

    public function read()
    {
        $types = empty($this->status) ? array_keys(MsggItem::getOptions('type')) : is_array($this->type) ? $this->type : [$this->type];
        $criteria = new CDbCriteria();
        $criteria->addInCondition('type', $types);
        $criteria->addColumnCondition(['status' => $this->status,]);
        foreach ($this->_orders as $order) {
            $criteria->order .= $order;
        }
        $configs = MsggConfig::model()->findAll($criteria);
        return array_map(function ($cofig) {
            return new ChannelConfig($cofig);
        }, $configs);
    }

    public function searchByKey(MsggConfig $config)
    {
        $criteria = new CDbCriteria;
        $criteria->addInCondition('type', array_keys(MsggItem::getOptions('type')));
        if (!empty($config->status)) {
            $criteria->addColumnCondition(array('status' => $config->status));
        }
        if ($config->type) {
            $criteria->addColumnCondition(array('type' => $config->type));
        }
        if ($config->searchKey !== '') {
            $criteria->addSearchCondition('config', $config->searchKey, true, 'OR');
            $criteria->addSearchCondition('name', $config->searchKey, true, 'OR');
            $criteria->addSearchCondition('status', $config->searchKey, true, 'OR');
        }
        return new CActiveDataProvider($config, array(
            'criteria' => $criteria,
        ));
    }


}